package com.dayaokeji.rhythmschoolstudent.client.home.meeting;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.common.zxing.CaptureActivity;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.GenerateQRCodeActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.PermissionGuideHelperActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.VieAnswerActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.bean.SignQrCodeContent;
import com.dayaokeji.rhythmschoolstudent.client.common.resource.SharedResourceActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.seat.ShowSeatActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.vote.VoteActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.adapter.InteractiveAdapter;
import com.dayaokeji.rhythmschoolstudent.client.home.course.adapter.MembersAvatarAdapter;
import com.dayaokeji.rhythmschoolstudent.client.home.data.MeetingInteractiveData;
import com.dayaokeji.rhythmschoolstudent.client.home.data.bean.ComponentBean;
import com.dayaokeji.rhythmschoolstudent.client.message.GroupsActivity;
import com.dayaokeji.rhythmschoolstudent.event.DeleteMeetingEvent;
import com.dayaokeji.rhythmschoolstudent.event.UpdateMeetingEvent;
import com.dayaokeji.rhythmschoolstudent.receiver.VieAnswerBean;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DialogUtils;
import com.dayaokeji.rhythmschoolstudent.utils.FileUtil;
import com.dayaokeji.rhythmschoolstudent.utils.FilenameUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ImageUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ItemDecorationUtil;
import com.dayaokeji.rhythmschoolstudent.utils.MD5Util;
import com.dayaokeji.rhythmschoolstudent.utils.ObjectUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionGroup;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.SignUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.rhythmschoolstudent.utils.WebTimeHandle;
import com.dayaokeji.rhythmschoolstudent.utils.WifiUtil;
import com.dayaokeji.rhythmschoolstudent.wiget.NotPermissionTipsDialog;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.Page;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.MeetingApi;
import com.dayaokeji.server_api.api.ResourceApi;
import com.dayaokeji.server_api.api.VieAnswerApi;
import com.dayaokeji.server_api.domain.Meeting;
import com.dayaokeji.server_api.domain.Member;
import com.dayaokeji.server_api.domain.SignResult;
import com.dayaokeji.server_api.domain.VieAnswer;
import com.dayaokeji.server_api.utils.FileFunctionFlag;
import com.google.gson.Gson;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;


/**
 * 会议详情
 */
public class MeetingDetailActivity extends BaseActivity {

    public static final String EXTRA_MEETING_ENTITY = "meeting_entity";

    private static final int SCAN_WIFI_QR_CODE_REQUEST_CODE = 1002;

    private static final int TAKE_SELF_PHOTO_REQUEST_CODE = 1004;


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.gv_meeting_interactive)
    RecyclerView gvMeetingInteractive;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_host)
    TextView tvHost;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_invitation_code)
    TextView tvInvitationCode;

    @BindView(R.id.btn_sign)
    Button btnSign;
    @BindView(R.id.btn_qr_code_sign)
    Button btnQrCodeSign;
    @BindView(R.id.iv_sign_success)
    ImageView ivSignSuccess;
    @BindView(R.id.tv_meeting_member_count)
    TextView tvMeetingMemberCount;
    @BindView(R.id.rv_meeting_members)
    RecyclerView rvMeetingMembers;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;

    private Meeting meeting;

    private final MeetingApi meetingApi = ApiUtils.getApi(MeetingApi.class);
    private final ResourceApi resourceApi = ApiUtils.getApi(ResourceApi.class);
    private final VieAnswerApi vieAnswerApi = ApiUtils.getApi(VieAnswerApi.class);
    private Call<ServerResponse<List<Integer>>> uploadCall;
    private Call<ServerResponse<SignResult>> signCall;
    private List<String> wifiList = new ArrayList<>();
    private Call<ServerResponse<Void>> deleteCall;
    private AppCompatDialog appCompatDialog;
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();
    private Integer signId = -1;
    private boolean isShowSignTime = false;
    private InteractiveAdapter componentAdapter;
    private Call<ServerResponse<Void>> goIntoCall;
    private Call<ServerResponse<List<Member>>> memberListCall;

    private MembersAvatarAdapter membersAvatarAdapter = new MembersAvatarAdapter();
    private Call<ServerResponse<Page<Meeting>>> findMeetingByIdCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeting_detail);
        setSupportActionBar(toolbar);
        meeting = (Meeting) getIntent().getSerializableExtra(EXTRA_MEETING_ENTITY);
        if (meeting == null) {
            ToastUtils.warning(R.string.data_incorrect);
            ActivityStackManager.finish();
        }
        setInteractive();
        init();
    }

    private void init() {
        setupView();
        backgroundGetWifiList();
        initData();
        setOnListener();
        startSign();
        showSignSuccess();
    }

    private void setupView() {
        rvMeetingMembers.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        rvMeetingMembers.setAdapter(membersAvatarAdapter);
    }

    private void showSignSuccess() {
        ivSignSuccess.setVisibility(meeting.getSignStatus() == 2? View.VISIBLE: View.INVISIBLE);
    }


    /**
     * 后台静默获取wifi列表
     */
    private void backgroundGetWifiList() {
        compositeDisposable.add(WifiUtil.getWifiList().subscribe(new Consumer<List<String>>() {
            @Override
            public void accept(List<String> strings) throws Exception {
                wifiList = strings;
            }
        }));
    }

    @SuppressLint("CheckResult")
    private Observable<Integer> checkWebTimeSignStatus() {
        //noinspection unchecked
        return WebTimeHandle.checkSignStatus(meeting).map(new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer status) throws Exception {
                if (status != null) {
                    switch (status) {
                        case 1:
                            signBtnStatus();
                            break;
                        case 2:
                            if (btnSign != null && btnQrCodeSign != null) {
                                btnSign.setText("未开始签到");
                                btnQrCodeSign.setEnabled(false);
                            }
                            break;
                        case 3:
                            if (btnSign != null && btnQrCodeSign != null) {
                                btnSign.setText("签到已结束");
                                btnSign.setEnabled(false);
                                btnQrCodeSign.setEnabled(false);
                            }
                            break;
                    }
                }
                return status;
            }
        });
    }

    @SuppressLint("CheckResult")
    private void startSign() {
        btnSign.setText("检测中....");
        compositeDisposable.add(checkWebTimeSignStatus().subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer status) throws Exception {
                if (status != null) {
                    if (status == 1 && meeting.getSignStatus() == 1) { // 签到
                        validateMacAddress();
                    }else if (status == 2 && meeting.getSignStatus() == 1){
                        compositeDisposable.add( WebTimeHandle.getSignDateTime(meeting).subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String s) throws Exception {
                                if (!TextUtils.isEmpty(s) && isShowSignTime){
                                    Snackbar.make(getWindow().getDecorView(), "签到将在"+s+"开始", Snackbar.LENGTH_LONG).show();
                                    isShowSignTime = false;
                                }
                            }
                        }));
                    }
                }
            }
        }));
    }

    private void signBtnStatus() {
        if (btnSign != null) {
            if (meeting.getSignStatus() == 2) { // 已签到
                if (meeting.getSignWay() == SignUtils.SIGN_WAY_TYPE_WIFI_PHOTO) {
                    btnSign.setEnabled(true);
                    btnSign.setText("拍照签到");
                } else {
                    btnSign.setText(SignUtils.getSignStatus(meeting.getSignStatus()));
                    btnSign.setEnabled(false);
                }

                if (!wifiList.isEmpty()) {
                    btnQrCodeSign.setText(R.string.generate_qr_code);
                    btnQrCodeSign.setEnabled(true);
                }
            } else { // 未签到
                if (meeting.getSignStatus() == 1) { // 可以签到
                    btnSign.setEnabled(true);
                    btnSign.setText(getString(R.string.a_key_to_sign));

                    if (btnQrCodeSign != null) {
                        btnQrCodeSign.setEnabled(true);
                        btnQrCodeSign.setText(getString(R.string.qr_code_sign));
                    }
                } else { // 不可以签到
                    btnSign.setText(SignUtils.getSignStatus(meeting.getSignStatus()));
                    btnSign.setEnabled(false);

                    if (!wifiList.isEmpty()) {
                        btnQrCodeSign.setText(R.string.generate_qr_code);
                        btnQrCodeSign.setEnabled(true);
                    }
                }
            }
        }
    }

    /**
     * get wifi list
     */
    @SuppressLint("CheckResult")
    private void checkWifiPermission() {
        final PermissionUtil.Build build = new PermissionUtil.Build();
        build.setPermissions(Constant.SIGN_PERMISSION_GROUP);
        build.setTips(getResources().getString(R.string.request_wifi_permission_tips));
        compositeDisposable.add(PermissionUtil.checkPermission(this, build).subscribe(new Consumer<PermissionUtil.PermissionResult>() {
            @Override
            public void accept(PermissionUtil.PermissionResult permissionResult) throws Exception {
                if (permissionResult.isHasAccess()) { // 有权限
                    addDisposable(WifiUtil.getWifiList().map(isSignFunc).map(notPermissionTips).subscribe(consumer));
                }
            }
        }));
    }

    private void validateMacAddress() {
        compositeDisposable.add(WifiUtil.getWifiList().map(isSignFunc).map(checkPermissionFunc).subscribe(consumer));
    }

    /**
     * 检查权限
     */
    private Function checkPermissionFunc = new Function<Boolean,Boolean>() {
        @Override
        public Boolean apply(Boolean aBoolean) throws Exception {
            if (aBoolean) {
                return true;
            }else{
                checkWifiPermission();
                return false;
            }
        }
    };

    /**
     * 没有权限提示
     */
    private Function notPermissionTips = new Function<Boolean,Boolean>() {
        @Override
        public Boolean apply(Boolean aBoolean) throws Exception {
            if (aBoolean) {
                return true;
            }else {
                NotPermissionTipsDialog.Companion.newInstance().show(getSupportFragmentManager(), "not_permission");
            }
            return false;
        }
    };

    /**
     * 判断是否可以签到
     */
    private Function isSignFunc = new Function<List<String>, Boolean>() {
        @Override
        public Boolean apply(List<String> wifis) throws Exception {
            if (wifis != null && !wifis.isEmpty()) { // 有wifi , 缓存列表
                wifiList.addAll( wifis);
                App.getInstance().getAcache().put(WifiUtil.COURSE_WIFI_CACHE_KEY, WifiUtil.wifiListJson(wifiList), WifiUtil.WIFI_CACHE_EXPIRED_TIME);
                return WifiUtil.checkMacAddress(meeting.getMck(),wifiList);
            } else { // 没有wifi列表 ， 取缓存列表
                final String wifiListJsonStr = App.getInstance().getAcache().getAsString(WifiUtil.COURSE_WIFI_CACHE_KEY);
                if (!TextUtils.isEmpty(wifiListJsonStr)) {
                    wifis = WifiUtil.wifiList(wifiListJsonStr);
                    if (wifis != null) {
                        wifiList.addAll(wifis);
                        if (wifiList.isEmpty()) {
                            showNotFoundWifiListDialog();
                        }else{
                            return WifiUtil.checkMacAddress(meeting.getMck(),wifiList);
                        }
                    }else{
                        return WifiUtil.checkMacAddress(meeting.getMck(),wifiList);
                    }
                }else{
                    return WifiUtil.checkMacAddress(meeting.getMck(),wifiList);
                }
            }
            return WifiUtil.checkMacAddress(meeting.getMck(),wifiList);
        }
    };

    /**
     * 签到
     */
    private Consumer consumer = new Consumer<Boolean>() {
        @Override
        public void accept(Boolean aBoolean) throws Exception {
            if (aBoolean) { // mac 地址验证通过 ，这时需要请求网络上传数据
                signNetHandle();
            }
        }
    };

    private void initData() {
        reqMeetingMembers();
        getSupportActionBar().setTitle(meeting.getName());
        tvTitle.setText(meeting.getName());
        tvAddress.setText(meeting.getRoomName());
        tvDate.setText(meeting.getActStartTime());
        if (meeting.getFacilitatorInfoList().size() > 0 && meeting.getFacilitatorInfoList().get(0) != null) {
            tvHost.setVisibility(View.VISIBLE);
            tvHost.setText(getString(R.string.host, meeting.getFacilitatorInfoList().get(0).getUserName()));
        }else{
            tvHost.setVisibility(View.GONE);
        }
        tvInvitationCode.setText(getString(R.string.invitation_code, String.valueOf(meeting.getId())));
    }

    private void setOnListener() {
        componentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ComponentBean componentBean = (ComponentBean)adapter.getData().get(position);
                Intent intent = new Intent();
                switch (componentBean.getIconResId()) {
                    case R.mipmap.ic_resources_share:
                        Meeting.FacilitatorInfo facilitatorInfo = null;
                        if (meeting.getFacilitatorInfoList().size() > 0) {
                            facilitatorInfo = meeting.getFacilitatorInfoList().get(0);
                        }
                        intent.setClass(MeetingDetailActivity.this, SharedResourceActivity.class);
                        intent.putExtra(SharedResourceActivity.EXTRA_REL_ID, meeting.getId());
                        intent.putExtra(SharedResourceActivity.EXTRA_REL_TYPE, Constant.FLAG_REL_TYPE_MEETING);
                        intent.putExtra(SharedResourceActivity.EXTRA_TEACHER_ID, facilitatorInfo != null?facilitatorInfo.getUserId():"");
                        intent.putExtra(SharedResourceActivity.EXTRA_RESOURSE_TYPE,FileFunctionFlag.MEETING);
                        startActivity(intent);
                        break;
                    case R.mipmap.ic_vote:
                        intent.setClass(MeetingDetailActivity.this, VoteActivity.class);
                        intent.putExtra(VoteActivity.EXTRA_REL_ID, meeting.getId());
                        intent.putExtra(VoteActivity.EXTRA_TEACHER_ID, Integer.valueOf(UserUtils.getUserInfo().getId()));
                        intent.putExtra(VoteActivity.EXTRA_REL_TYPE, Constant.FLAG_REL_TYPE_MEETING);
                        startActivity(intent);
                        break;
                    case R.mipmap.ic_seat:
                        if (!TextUtils.isEmpty(meeting.getUserSeat())) {
                            intent.setClass(MeetingDetailActivity.this, ShowSeatActivity.class);
                            intent.putExtra(ShowSeatActivity.EXTRA_USER_SEAT, meeting.getUserSeat());
                            intent.putExtra(ShowSeatActivity.EXTRA_ROOM_ID, String.valueOf(meeting.getRoomId()));
                            startActivity(intent);
                        } else {
                            ToastUtils.info("未安排座位");
                        }
                        break;
                    case R.mipmap.ic_voice:
                        startVoice();
                        break;
                    case R.mipmap.ic_discussion_group:
                        GroupsActivity.Companion.navigation(MeetingDetailActivity.this,meeting.getDetailId(),Constant.FLAG_REL_TYPE_MEETING);
                        break;
                }
            }
        });

        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshMeetingDetail();
            }
        });
    }

    /**
     * 刷新会议详情
     */
    private void refreshMeetingDetail() {
        findMeetingByIdCall = meetingApi.findMeetingById(String.valueOf(meeting.getDetailId()),1,1);
        findMeetingByIdCall.enqueue(new ServerCallback<Page<Meeting>>(this,"正在查询会议数据...") {
            @Override
            public void onResponse(boolean success, ServerResponse<Page<Meeting>> response) {
                if (success) {
                    if (response.getBody() != null && !response.getBody().getList().isEmpty()) {
                        MeetingDetailActivity.this.meeting = response.getBody().getList().get(0);
                        startSign();
                        signBtnStatus();
                        showSignSuccess();
                        EventBus.getDefault().post(new UpdateMeetingEvent());
                        if (swipeRefresh != null) {
                            if (swipeRefresh.isRefreshing()) {
                                swipeRefresh.setRefreshing(false);
                            }
                        }
                    }
                }
            }
        });
    }


    /**
     * 抢答
     */
    @SuppressLint("CheckResult")
    private void startVoice() {
        final PermissionUtil.Build build = new PermissionUtil.Build();
        build.setPermissions(new String[]{Permission.RECORD_AUDIO});
        build.setTips("请允许使用录音权限，方便您进行抢答");
        compositeDisposable.add(PermissionUtil.checkPermission(MeetingDetailActivity.this, build).subscribe(voiceConsumer));
    }

    private Consumer voiceConsumer = new Consumer<PermissionUtil.PermissionResult>() {
        @SuppressLint("CheckResult")
        @Override
        public void accept(PermissionUtil.PermissionResult permissionResult) throws Exception {
            if (permissionResult.isHasAccess()) {
                vieAnswerQuery();
            }else{
                final PermissionUtil.Build build = new PermissionUtil.Build();
                build.setPermissions(new String[]{Permission.RECORD_AUDIO});
                build.setTips("请允许使用录音权限，方便您进行抢答");
                compositeDisposable.add(PermissionUtil.checkPermission(MeetingDetailActivity.this, build).subscribe(voiceConsumer));
            }
        }
    };

    private void vieAnswerQuery() {
        final VieAnswer vieAnswer = new VieAnswer(Constant.FLAG_REL_TYPE_COURSE, meeting.getDetailId());
        goIntoCall = vieAnswerApi.goInto(vieAnswer);
        goIntoCall.enqueue(new ServerCallback<Void>(this,"正在抢答中...") {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    if (meeting.getFacilitatorInfoList().size() > 0) {
                        final Meeting.FacilitatorInfo facilitatorInfo = meeting.getFacilitatorInfoList().get(0);
                        if (facilitatorInfo != null) {
                            long imId = Long.parseLong(UserUtils.getUserInfo().getUniversityId()+facilitatorInfo.getWorkNo());
                            VieAnswerBean vieAnswerBean = new VieAnswerBean(Constant.FLAG_REL_TYPE_COURSE, meeting.getId(), meeting.getDetailId(), imId, facilitatorInfo.getUserName(),false);
                            VieAnswerActivity.Companion.navigation(MeetingDetailActivity.this, vieAnswerBean);
                        }
                    }
                }
            }
        });

    }

    @OnClick({
            R.id.btn_sign,
            R.id.btn_qr_code_sign
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_sign:
                isShowSignTime = true;
                if (meeting.getSignStatus() == 2 && meeting.getSignWay() == SignUtils.SIGN_WAY_TYPE_WIFI_PHOTO){
                    SignUtils.showTakePhotoDialog(MeetingDetailActivity.this, takeSelfPhotoListener);
                }else{
                    startSign();
                }
                break;
            case R.id.btn_qr_code_sign:
                if (meeting.getSignStatus() == 2) {
                    if (!wifiList.isEmpty()) {
                        Intent generateQrCodeIntent = new Intent();
                        generateQrCodeIntent.setClass(MeetingDetailActivity.this, GenerateQRCodeActivity.class);
                        generateQrCodeIntent.putExtra(GenerateQRCodeActivity.EXTRA_SIGN_WIFI, meeting.getMck());
                        generateQrCodeIntent.putExtra(GenerateQRCodeActivity.EXTRA_COURSE_TITLE, meeting.getName() + "二维码");
                        startActivity(generateQrCodeIntent);
                    } else {
                        Snackbar.make(getWindow().getDecorView(), "未获取到WIFI列表信息，无法生成二维码",  Snackbar.LENGTH_LONG).show();
                    }

                } else {
                    showQRCodeDialog();
                }
                break;
        }
    }

    private void showQRCodeDialog() {
        final android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setTitle("二维码签到");
        builder.setItems(new String[]{"扫描二维码", "生成二维码"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                switch (which) {
                    case 0:
                        intent.setClass(MeetingDetailActivity.this, CaptureActivity.class);
                        intent.putExtra("autoEnlarged",true);
                        startActivityForResult(intent, SCAN_WIFI_QR_CODE_REQUEST_CODE);
                        break;
                    case 1:
                        if (!wifiList.isEmpty()) {
                            intent.setClass(MeetingDetailActivity.this, GenerateQRCodeActivity.class);
                            intent.putExtra(GenerateQRCodeActivity.EXTRA_SIGN_WIFI, meeting.getMck());
                            intent.putExtra(GenerateQRCodeActivity.EXTRA_COURSE_TITLE, meeting.getName() + "二维码");
                            startActivity(intent);
                        } else {
                            ToastUtils.warning("未获取到wifi信息，请选择<扫描二维码>进行签到");
                        }

                        break;
                }
            }
        });
        builder.setNegativeButton("取消", null);
        android.support.v7.app.AlertDialog show = builder.show();
        show.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
    }


    /**
     * 未获取到wifi列表提示dialog
     */
    private void showNotFoundWifiListDialog() {
        SpannableStringBuilder notFountWIFIListTips = SignUtils.getNotFountWifiListTips(this, permissionGuideListener);
        if (notFountWIFIListTips != null) {
            appCompatDialog = DialogUtils.getAppCompatDialog(this, R.layout.dialog_permission_prompt);
            TextView tips = (TextView) appCompatDialog.findViewById(R.id.tv_permission_tips);
            tips.setText(notFountWIFIListTips);
            tips.setMovementMethod(LinkMovementMethod.getInstance());
            appCompatDialog.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (appCompatDialog != null && appCompatDialog.isShowing()) {
                        appCompatDialog.dismiss();
                    }
                }
            });
        }
    }

    /**
     * 开启wifi,位置信息详细引导
     */
    private View.OnClickListener permissionGuideListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (appCompatDialog != null) {
                appCompatDialog.dismiss();
            }
            startActivity(new Intent(MeetingDetailActivity.this, PermissionGuideHelperActivity.class));
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_del_meeting:
                delMeeting();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 设置互动组件
     */
    private void setInteractive() {
        componentAdapter = new InteractiveAdapter(MeetingInteractiveData.getMeetingUserData());
        gvMeetingInteractive.setLayoutManager(new GridLayoutManager(this,3));
        gvMeetingInteractive.addItemDecoration(ItemDecorationUtil.horizontalDividerItemDecoration(this, AndroidUtils.dp2px(20)));
        gvMeetingInteractive.setAdapter(componentAdapter);
    }



    /**
     * 签到请求
     */
    private void signNetHandle() {
        btnSign.setText("正在签到...");
        btnSign.setEnabled(false);
        Map<String, String> params = new HashMap<>();
        params.put("meetingId", String.valueOf(meeting.getId()));
        params.put("detailId",String.valueOf(meeting.getDetailId()));
        params.put("userId", UserUtils.getUserInfo().getId());
        params.put("mck", AndroidUtils.getMobileOnlyFlag(this));
        params.put("status", "2");
        params.put("remark", "无");
        signCall = meetingApi.sign(params);
        signCall.enqueue(new ServerCallback<SignResult>(this, "正在签到...") {
            @Override
            public void onResponse(boolean success, ServerResponse<SignResult> response) {
                if (success) {
                    SignResult signResult = response.getBody();
                    signId = signResult.getId();
                    if (btnSign != null && meeting.getSignWay() == SignUtils.SIGN_WAY_TYPE_WIFI_PHOTO) {
                        btnSign.setEnabled(true);
                        btnSign.setText("拍照签到");
                        SignUtils.showTakePhotoDialog(MeetingDetailActivity.this, takeSelfPhotoListener);
                    }else if (btnSign != null){
                        btnSign.setEnabled(false);
                    }
                    meeting.setSignStatus(signResult.getStatus());
                    signBtnStatus();
                    showSignSuccess();
                    EventBus.getDefault().post(new UpdateMeetingEvent());
                }else{
                    if (btnSign != null) {
                        btnSign.setEnabled(true);
                        btnSign.setText(getString(R.string.a_key_to_sign));
                    }
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<SignResult>> call, Throwable t) {
                super.onFailure(call, t);
                if (btnSign != null) {
                    btnSign.setEnabled(true);
                    btnSign.setText(getString(R.string.a_key_to_sign));
                }
            }
        });
    }

    /**
     * 拍摄本人照片
     */
    private View.OnClickListener takeSelfPhotoListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            photoSign();
        }
    };

    /**
     * 删除会议
     */
    private void delMeeting() {

        DialogUtils.getAlertDialog(this, "提示", "是否删除当前会议？", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                delMeetingHandle();
            }
        });
    }

    /**
     * 删除会议处理
     */
    private void delMeetingHandle() {
        Map<String, String> params = new HashMap<>();
        params.put("id", String.valueOf(meeting.getId()));
        deleteCall = meetingApi.delete(params);
        deleteCall.enqueue(new ServerCallback<Void>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    ToastUtils.success("删除成功");
                    EventBus.getDefault().post(new DeleteMeetingEvent(meeting));
                    ActivityStackManager.finish();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (SCAN_WIFI_QR_CODE_REQUEST_CODE == requestCode) {
            if (null != data) {
                Bundle extras = data.getExtras();
                if (null == extras) {
                    ToastUtils.warning("未获取到解析的内容");
                    return;
                }

                String result = data.getStringExtra("result");
                if (!TextUtils.isEmpty(result)) {
                    paserQRCodeResult(result);
                }else{
                    ToastUtils.info("二维码数据为空");
                }
            }
        } else if (TAKE_SELF_PHOTO_REQUEST_CODE == requestCode) {
            if (resultCode != RESULT_CANCELED) {
                final File captureImageFile = ImageUtil.getCaptureImageFile();
                if (captureImageFile != null) {
                    compressFile(captureImageFile);
                }
            }
        }
    }

    /**
     * 压缩文件
     *
     * @param captureImageFile
     */
    @SuppressLint("CheckResult")
    private void compressFile(File captureImageFile) {
        final ProgressDialog progressDialog = new ProgressDialog(MeetingDetailActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在上传...");
        progressDialog.show();
        if (captureImageFile != null) {
            ImageUtil.ImageWaterMarkTask(MeetingDetailActivity.this,captureImageFile).subscribe(new Consumer<File>() {
                @Override
                public void accept(File file) throws Exception {
                    if (file != null) {
                        uploadPhoto(file, progressDialog);
                    }
                }
            });
        }
    }

    /**
     * 多次图片签到上传
     */
    @SuppressLint("CheckResult")
    private void photoSign() {
        checkWebTimeSignStatus().subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                if (integer == 1 && meeting.getSignStatus() == 2) {
                    if (PermissionUtil.hasPermission(PermissionGroup.CAMERA_AND_STORE)) {
                        ImageUtil.captureImageByCamera(MeetingDetailActivity.this, TAKE_SELF_PHOTO_REQUEST_CODE);
                    }else{
                        final PermissionUtil.Build build = new PermissionUtil.Build();
                        build.setPermissions(PermissionGroup.CAMERA_AND_STORE);
                        build.setTips("请允许我们访问拍照和存储权限，以方便您进行拍照签到");
                        compositeDisposable.add(PermissionUtil.checkPermission(MeetingDetailActivity.this, build).subscribe(cameraConsumer));
                    }
                }
            }
        });
    }

    private Consumer cameraConsumer = new Consumer<PermissionUtil.PermissionResult>() {
        @SuppressLint("CheckResult")
        @Override
        public void accept(PermissionUtil.PermissionResult permissionResult) throws Exception {
            if (permissionResult.isHasAccess()) { // 允许拍照
                ImageUtil.captureImageByCamera(MeetingDetailActivity.this, TAKE_SELF_PHOTO_REQUEST_CODE);
            }else{ // 未获取到拍照权限
                final PermissionUtil.Build build = new PermissionUtil.Build();
                build.setPermissions(PermissionGroup.CAMERA_AND_STORE);
                build.setTips("请允许我们访问拍照权限，以方便您进行拍照签到");
                compositeDisposable.add(PermissionUtil.checkPermission(MeetingDetailActivity.this, build).subscribe(cameraConsumer));
            }
        }
    };

    /**
     * 上传图片
     */
    private void uploadPhoto(File file, final ProgressDialog progressDialog) {
        if (UserUtils.getUserInfo() != null) {
            if (file != null) {
                String fileExtension = FilenameUtils.getExtension(file.getPath());
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("myfiles", file.getName(), requestBody);
                uploadCall = resourceApi.upload(filePart,
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(FileUtil.getFileType(fileExtension))),
                        RequestBody.create(MediaType.parse("text/plain"), file.getName()),
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(FileFunctionFlag.MEETING_PHOTO_SIGN)),
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(signId)),
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(Boolean.FALSE)));
                uploadCall.enqueue(new ServerCallback<List<Integer>>() {
                    @Override
                    public void onResponse(boolean success, ServerResponse<List<Integer>> response) {
                        if (success) {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            ToastUtils.success("上传成功");
                        }
                    }
                });
            }
        } else {
            ToastUtils.warning("帐号异常，请重新登录之后重试");
        }
    }

    /**
     * 解析扫描的二维码数据
     *
     * @param result
     */
    private void paserQRCodeResult(String result) {
        try {
            final Gson gson = new Gson();
            SignQrCodeContent signQrCodeContent = gson.fromJson(result, SignQrCodeContent.class);
            String checkCode = signQrCodeContent.getDate() + "dayaokeji";
            final String md5CheckCode = MD5Util.md5(checkCode);
            if (ObjectUtils.equals(md5CheckCode, signQrCodeContent.getCheckcode().toUpperCase())) {
                if (SignUtils.isExpiredTime(signQrCodeContent.getDate())) {
                    wifiList = signQrCodeContent.getLoc_array();
                    if (WifiUtil.checkMacAddress(meeting.getMck(),wifiList)) {
                        signNetHandle();
                    }
                }
            } else {
                ToastUtils.warning("二维码数据无效");
            }

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.error("扫描二维码结果解析失败");
        }
    }


    private void reqMeetingMembers() {
        memberListCall = meetingApi.member(meeting.getId());
        memberListCall.enqueue(new ServerCallback<List<Member>>() {
            @Override
            public void onResponse(boolean success, ServerResponse<List<Member>> response) {
                if (success) {
                    List<Member> members = response.getBody();
                    if (members != null && !members.isEmpty()) {
                        membersAvatarAdapter.setNewData(members);
                    }
                    if (tvMeetingMemberCount != null) {
                        tvMeetingMemberCount.setText(String.valueOf(members.size()));
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (signCall != null) {
            signCall.cancel();
        }

        if (deleteCall != null) {
            deleteCall.cancel();
        }

        if (memberListCall != null) {
            memberListCall.cancel();
        }
        super.onDestroy();
    }
}
